"""
角色管理API端点
"""
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status, Query
from app.schemas.role import RoleCreate, RoleUpdate, RoleResponse
from app.api.deps import get_current_user, get_db
from app.core.permissions import require_permission
from app.core.response import success_response, error_response, ApiResponse
from app.services.role_service import RoleService, DEFAULT_ROLES
from motor.motor_asyncio import AsyncIOMotorDatabase

router = APIRouter()


@router.get("/options", response_model=ApiResponse, summary="获取角色选项（公开接口）")
async def get_role_options(
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """获取角色选项列表（公开接口，用于注册页面）"""
    try:
        role_options = await RoleService.get_role_options(db)
        return success_response(
            data=role_options,
            message="获取角色选项成功"
        )
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取角色选项失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.get("/all", response_model=ApiResponse, summary="获取所有角色（不分页）")
async def get_all_roles(
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """获取所有角色（不分页）"""
    try:
        # 检查权限
        require_permission(current_user, "role:view")
        
        # 调用服务层获取所有角色
        roles = await RoleService.get_all_roles(db)
        
        # 转换数据格式
        role_list = [RoleResponse(**role).model_dump() for role in roles]
        
        return success_response(
            data=role_list,
            message="获取角色列表成功"
        )
    except HTTPException:
        # 权限错误等HTTP异常直接抛出，由FastAPI处理
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取角色列表失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.get("", response_model=ApiResponse, summary="获取所有角色")
@router.get("/", response_model=ApiResponse, summary="获取所有角色")
async def get_roles(
    role_status: Optional[str] = Query(None, description="角色状态筛选，可选值：active, inactive"),
    is_system: Optional[bool] = Query(None, description="是否系统角色筛选，True: 只返回系统角色, False: 只返回自定义角色"),
    scope: Optional[str] = Query(None, description="角色作用域筛选，可选值：system, project"),
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    获取所有角色
    支持按状态和类型（系统角色/自定义角色）筛选
    """
    try:
        # 检查权限
        require_permission(current_user, "role:view")
        
        # 调用服务层获取角色
        roles = await RoleService.get_roles(db, status=role_status, is_system=is_system, scope=scope)
        
        # 转换数据格式
        role_list = [RoleResponse(**role).model_dump() for role in roles]
        
        return success_response(
            data=role_list,
            message="获取角色列表成功"
        )
    except HTTPException:
        # 权限错误等HTTP异常直接抛出，由FastAPI处理
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取角色列表失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.get("/system", response_model=ApiResponse, summary="获取所有系统角色")
async def get_system_roles(
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    获取所有系统角色
    系统角色是预定义的角色，权限由系统自动管理
    """
    try:
        # 检查权限
        require_permission(current_user, "role:view")
        
        # 调用服务层获取系统角色
        roles = await RoleService.get_system_roles(db)
        
        # 转换数据格式
        role_list = [RoleResponse(**role).model_dump() for role in roles]
        
        return success_response(
            data=role_list,
            message="获取系统角色列表成功"
        )
    except HTTPException:
        # 权限错误等HTTP异常直接抛出，由FastAPI处理
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取系统角色列表失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.get("/custom", response_model=ApiResponse, summary="获取所有自定义角色")
async def get_custom_roles(
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    获取所有自定义角色
    自定义角色是用户创建的角色，权限可以自定义
    """
    try:
        # 检查权限
        require_permission(current_user, "role:view")
        
        # 调用服务层获取自定义角色
        roles = await RoleService.get_custom_roles(db)
        
        # 转换数据格式
        role_list = [RoleResponse(**role).model_dump() for role in roles]
        
        return success_response(
            data=role_list,
            message="获取自定义角色列表成功"
        )
    except HTTPException:
        # 权限错误等HTTP异常直接抛出，由FastAPI处理
        raise
    except Exception as e:
        return error_response(
            error_type="INTERNAL_ERROR",
            message=f"获取自定义角色列表失败: {str(e)}",
            code=status.HTTP_500_INTERNAL_SERVER_ERROR
        )


@router.post("", response_model=ApiResponse, summary="创建角色")
@router.post("/", response_model=ApiResponse, summary="创建角色")
async def create_role(
    role_data: RoleCreate,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """创建新角色"""
    try:
        # 检查权限
        require_permission(current_user, "role:create")
        
        # 调用服务层创建角色
        created_role = await RoleService.create_role(db, role_data)
        
        return success_response(
            data=RoleResponse(**created_role).model_dump(),
            message="角色创建成功"
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail=str(e)
        )
    except Exception as e:
        return error_response(f"创建角色失败: {str(e)}")


@router.get("/{role_id}", response_model=ApiResponse, summary="获取角色详情")
async def get_role(
    role_id: str,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    获取角色详情
    如果是系统角色，会返回最新的权限定义（从 ROLE_PERMISSIONS 获取）
    """
    try:
        # 检查权限
        require_permission(current_user, "role:view")
        
        # 调用服务层获取角色（包括最新权限）
        role = await RoleService.get_role_with_permissions(db, role_id)
        
        return success_response(
            data=RoleResponse(**role).model_dump(),
            message="获取角色详情成功"
        )
    except ValueError as e:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail=str(e)
        )
    except Exception as e:
        return error_response(f"获取角色详情失败: {str(e)}")


@router.put("/{role_id}", response_model=ApiResponse, summary="更新角色")
async def update_role(
    role_id: str,
    role_data: RoleUpdate,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """更新角色"""
    try:
        # 检查权限
        require_permission(current_user, "role:update")
        
        # 调用服务层更新角色
        updated_role = await RoleService.update_role(db, role_id, role_data)
        
        return success_response(
            data=RoleResponse(**updated_role).model_dump(),
            message="角色更新成功"
        )
    except ValueError as e:
        if "不存在" in str(e):
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=str(e)
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=str(e)
            )
    except Exception as e:
        return error_response(f"更新角色失败: {str(e)}")


@router.delete("/{role_id}", response_model=ApiResponse, summary="删除角色")
async def delete_role(
    role_id: str,
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """删除角色"""
    try:
        # 检查权限
        require_permission(current_user, "role:delete")
        
        # 调用服务层删除角色
        await RoleService.delete_role(db, role_id)
        
        return success_response(
            message="角色删除成功"
        )
    except ValueError as e:
        if "不存在" in str(e):
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail=str(e)
            )
        else:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=str(e)
            )
    except Exception as e:
        return error_response(f"删除角色失败: {str(e)}")


@router.post("/init", response_model=ApiResponse, summary="初始化系统角色（覆盖初始化）")
async def init_default_roles(
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    初始化系统角色（覆盖初始化）
    创建所有预定义的系统角色，如果角色已存在且是系统角色，会完全覆盖其定义
    （包括名称、描述、权限等），确保与代码定义完全一致
    系统角色的权限由系统自动管理，不允许手动修改
    注意：此操作会覆盖现有系统角色的所有字段，但不会影响自定义角色
    """
    try:
        # 检查权限
        require_permission(current_user, "role:create")
        
        # 调用服务层初始化系统角色（覆盖初始化）
        result = await RoleService.init_default_roles(db)
        created_count = result.get("created_count", 0)
        updated_count = result.get("updated_count", 0)
        total_count = result.get("total_count", len(DEFAULT_ROLES))
        
        # 构建消息
        messages = []
        if created_count > 0:
            messages.append(f"创建了 {created_count} 个系统角色")
        if updated_count > 0:
            messages.append(f"覆盖更新了 {updated_count} 个系统角色")
        if created_count == 0 and updated_count == 0:
            messages.append(f"所有 {total_count} 个系统角色均已存在且定义已同步")
        
        return success_response(
            data=result,
            message="；".join(messages) if messages else "初始化完成"
        )
    except Exception as e:
        return error_response(f"初始化系统角色失败: {str(e)}")


@router.post("/sync-permissions", response_model=ApiResponse, summary="同步系统角色权限")
async def sync_system_role_permissions(
    current_user: dict = Depends(get_current_user),
    db: AsyncIOMotorDatabase = Depends(get_db)
):
    """
    同步所有系统角色的权限到数据库
    确保数据库中系统角色的权限与 ROLE_PERMISSIONS 定义一致
    仅适用于系统角色，自定义角色的权限不受影响
    """
    try:
        # 检查权限
        require_permission(current_user, "role:update")
        
        # 调用服务层同步权限
        result = await RoleService.sync_all_system_roles(db)
        synced_count = result.get("synced_count", 0)
        failed_count = result.get("failed_count", 0)
        total_count = result.get("total_count", 0)
        
        # 构建消息
        messages = []
        if synced_count > 0:
            messages.append(f"成功同步 {synced_count} 个系统角色的权限")
        if failed_count > 0:
            messages.append(f"{failed_count} 个系统角色同步失败")
        if synced_count == 0 and failed_count == 0:
            messages.append(f"所有 {total_count} 个系统角色的权限已是最新")
        
        return success_response(
            data=result,
            message="；".join(messages)
        )
    except Exception as e:
        return error_response(f"同步系统角色权限失败: {str(e)}")